package com.baozheyangken.ai_learn.service.serviceImpl;

import com.baozheyangken.ai_learn.context.BaseContext;
import com.baozheyangken.ai_learn.mapper.CourseMapper;
import com.baozheyangken.ai_learn.mapper.UserMapper;
import com.baozheyangken.ai_learn.pojo.entity.Course;
import com.baozheyangken.ai_learn.pojo.vo.CourseVO;
import com.baozheyangken.ai_learn.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    // 创建课程
    @Override
    @Transactional
    public Course createCourse(CourseVO courseVO) {
        Integer userId = BaseContext.getCurrentId();
        //todo 如果不是教师或管理员则无法创建课程

        Course course = new Course();
        BeanUtils.copyProperties(courseVO, course);
        course.setUserId(Long.valueOf(userId));
        course.setCreatedAt(LocalDateTime.now());
        course.setUpdatedAt(LocalDateTime.now());
        courseMapper.save(course);
        return course;
    }

    // 获取所有课程
    @Override
    public List<Course> getAllCourses() {
        return courseMapper.findAll();
    }

    // 根据ID获取课程
    @Override
    public Course getCourseById(Integer id) {
        return courseMapper.findById(id);
    }

    // 更新课程信息
    @Override
    public Course updateCourse(Integer id, CourseVO courseVO) {
        Course course = courseMapper.findById(id);
        BeanUtils.copyProperties(courseVO, course);

        //todo 更新修改课程的用户，判断当前用户是否有权限修改课程

        course.setUserId(Long.valueOf(BaseContext.getCurrentId()));
        course.setUpdatedAt(LocalDateTime.now());
        courseMapper.updateCourse(course);
        return course;
    }

    // 删除课程（逻辑删除）
    @Override
    public void deleteCourse(Integer id) {
        // 由于数据库表没有 status 字段，无法进行逻辑删除，可考虑物理删除
        courseMapper.deleteById(id);
    }

    // 根据学科和年级筛选课程
    @Override
    public List<Course> getCoursesBySubjectAndGrade(String subject, String grade) {
        return courseMapper.findBySubjectAndGrade(subject, grade);
    }

    // 根据教师ID获取课程列表


    // 搜索课程
    @Override
    public List<Course> searchCourses(String keyword) {
        return courseMapper.searchByKeyword(keyword);
    }
}